<script setup lang="jsx">
import {ref, computed, onMounted} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {
  ChatBubbleSmileIcon,
  ChatMessageIcon,
  FlagIcon,
  NoExpressionIcon,
  TaskAddIcon,
  UsergroupIcon
} from "tdesign-icons-vue-next";
import {EventSourcePolyfill} from "event-source-polyfill";
import {useUserStore} from "@/stores/user.js";
import {disconnectSse} from "@/api/sse.js";
import {unreadInitial} from "@/api/notice.js";
import {useActivityMessage} from "@/stores/activityMessage.js";

const URL = import.meta.env.VITE_BASE_API_URL
const ICP_BEI_AN_HAO = import.meta.env.VITE_ICP_BEI_AN_HAO
const GONG_AN_BEI_AN_HAO = import.meta.env.VITE_GONG_AN_BEI_AN_HAO
const GONG_AN_BEI_AN_WEB = import.meta.env.VITE_GONG_AN_BEI_AN_WEB
const VITE_PROJECT_FRONT = import.meta.env.VITE_PROJECT_FRONT
const VITE_PROJECT_BACKEND = import.meta.env.VITE_PROJECT_BACKEND
const router = useRouter();
const route = useRoute();
const collapsed = ref(false);
const iconUrl = ref('https://hruiworks-private-1.oss-cn-hangzhou.aliyuncs.com/campus-group/logo/campus-group-logo-long.png');
const userStore = useUserStore()
const activityMessage = useActivityMessage()


// 添加一个状态控制是否显示通知请求按钮
const showNotifyWindow = ref(false)



// 通知权限方法 ---------------------------------------------------------------------
function notifyCheck() {
  if (!("Notification" in window)) {
    alert("This browser does not support desktop notification");
  }
// 检查用户是否同意接受通知
  else if (Notification.permission === "granted") {
    // const notification = new Notification("Hi there!");
  }
// 否则我们需要向用户获取权限
  else if (Notification.permission !== "denied") {
    showNotifyWindow.value = true
  }
}
function notify(bool) {
  if (!("Notification" in window)) {
    alert("This browser does not support desktop notification");
  }
// 检查用户是否同意接受通知
  else if (bool === false) {
    // const notification = new Notification("Hi there!");
  }
// 否则我们需要向用户获取权限
  else if (bool === true) {
    Notification.requestPermission().then((permission )=> {
      // 如果用户接受权限，我们就可以发起一条消息
      if (permission === "granted") {
        // const notification = new Notification("Hi there!");
      }
    });
    showNotifyWindow.value = false
  }
}



onMounted(async ()=>{
  // 获取通知权限
  notifyCheck()
  // 初始化未读信息
  const res = await unreadInitial(userStore)
  activityMessage.unreadCount = res.data.data
})

// 新活动未读消息 ------------------------------------------------------------------
const activityUnread = ref(0)

// 导航栏 -----------------------------------------------------------
const activeValue = computed(() => {
  switch (route.path) {
    case '/user/activity':
      return 'activity';
    case '/user/activity/content':
      return 'activity';
    case '/user/activity/group':
      return 'activity';
    case '/user/message/activity':
      return 'message_activity';
    case '/user/message/group':
      return 'message_group';
    case '/user/activity/apply':
      return 'activity_apply';
    case '/user/home':
      return 'user_home';
    case '/user/info':
      return 'user_info';
    case '/user/group':
      return 'user_group';
    case '/user/feedback':
      return 'feedback';
    default:
      return 'user_home';
  }
});

const changeCollapsed = () => {
  collapsed.value = !collapsed.value;
  iconUrl.value = collapsed.value
      ? 'https://hruiworks-private-1.oss-cn-hangzhou.aliyuncs.com/campus-group/logo/campus-group-logo-one.png'
      : 'https://hruiworks-private-1.oss-cn-hangzhou.aliyuncs.com/campus-group/logo/campus-group-logo-long.png';
};

const changeHandler = (activeValue) => {
  switch (activeValue) {
    case 'activity':
      router.push('/user/activity');
      break
    case 'activity_apply':
      router.push('/user/activity/apply');
      break
    case 'user_home':
      router.push('/user/home');
      break;
    case 'user_info':
      router.push('/user/info');
      break;
    case 'login':
      router.push('/login');
      eventSource.close(); // 确保在错误发生时关闭连接
      break;
    case 'user_group':
      router.push('/user/group');
      break;
    case 'feedback':
      router.push('/user/feedback');
      break;
    case 'message_activity':
      router.push('/user/message/activity');
      break;
    case 'message_group':
      router.push('/user/message/group');
      break;
    default:
      break;
  }
};

// 活动未读消息 ------------------------------------------------------------
// set(key, value): 添加或更新键值对
// get(key): 根据键获取对应的值
// has(key): 判断Map中是否包含指定的键
// delete(key): 删除指定的键值对
// clear(): 清空Map中的所有键值对

// const activityMessage = new Map()

// SSE ---------------------------------------------------------------------
const eventSource = new EventSourcePolyfill(URL+'/sse/events', {
  headers: {
    'User-Token': userStore.$state.jwtEntity.jwt,
    'User-Secret-Key': userStore.$state.jwtEntity.signKeyStr
  }
});

let jsonObject;
eventSource.onmessage = function(event) {

  jsonObject = JSON.parse(event.data);
  if (jsonObject.messageType === "group_start_message") {
    visible2.value = true;
    dynamicHTML = '<div>活动名: '+jsonObject.data.activity.activityName+'</div>'
    + '<div>开始时间: '+jsonObject.data.group.startTime+'</div>'
    + '<div>结束时间: '+jsonObject.data.group.endTime+'</div>';
    if (Notification.permission === "granted") {
      // win窗口
      const notification = new Notification("Campus-Group",{
        body: jsonObject.data.activity.activityName+'活动即将开始',
        icon: 'https://hruiworks-private-1.oss-cn-hangzhou.aliyuncs.com/campus-group/logo/campus-group-logo-one.png'
      });
    }
  }
  else if (jsonObject.messageType === "new_member") {
    if (Notification.permission === "granted") {
      // win窗口
      const notification = new Notification("Campus-Group",{
        body: jsonObject.data,
        icon: 'https://hruiworks-private-1.oss-cn-hangzhou.aliyuncs.com/campus-group/logo/campus-group-logo-one.png'
      });
    }

  }
  else if(jsonObject.messageType === "new_activity") {
    activityMessage.unreadCount++
    console.log(activityMessage.unreadCount)
  } else {
    console.log(event.data)
  }
};

eventSource.onerror = function(error) {
  console.error("EventSource failed:", error);
  eventSource.close(); // 确保在错误发生时关闭连接
};

let isUnloading = false;

// 监听页面隐藏（切换标签页）
document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') {
    // 标签页被隐藏（如切换标签页），但不关闭连接
    console.log('标签页切换到后台，保持连接');
  }
});

// 监听页面完全卸载（关闭或刷新）
window.addEventListener('pagehide', async (event) => {
  if (!event.persisted) { // 排除浏览器前进/后退缓存
    isUnloading = true;
    await disconnectSse(userStore);
    eventSource.close();

    console.log('页面关闭或刷新，关闭连接');
  }
});

// 兜底处理（兼容不支持 pagehide 的浏览器）
window.addEventListener('beforeunload', async () => {
  if (!isUnloading) { // 避免重复关闭
    await disconnectSse(userStore);
    eventSource.close();
    console.log('通过 beforeunload 关闭连接');
  }
});

// 消息窗口 ----------------------------------------------------------
const visible2 = ref(false);
const close2 = () => {
  visible2.value = false;
};

let dynamicHTML =''


</script>

<template>
  <t-layout style="height: 100vh">
    <t-aside style="height: 100%; width: auto">
      <t-menu
          theme="light"
          :value="activeValue"
          :collapsed="collapsed"
          @change="changeHandler"
          style="height: 100%;"
      >
        <template #logo>
          <img :width="collapsed ? 35 : 185" :src="iconUrl" alt="logo"/>
        </template>
        <t-menu-group title="活动相关">
          <t-menu-item value="activity">
            <template #icon>
              <FlagIcon />
            </template>
            活动
          </t-menu-item>
          <t-menu-item value="user_group">
            <template #icon>
              <UsergroupIcon />
            </template>
            团队
          </t-menu-item>
          <t-menu-item value="activity_apply">
            <template #icon>
              <TaskAddIcon />
            </template>
            活动申请
          </t-menu-item>
          <t-menu-item value="feedback">
            <template #icon>
              <NoExpressionIcon />
            </template>
            活动反馈
          </t-menu-item>
        </t-menu-group>
        <t-menu-group title="消息">
<!--          <t-menu-item value="message_group">-->
<!--            <template #icon>-->
<!--              <ChatBubbleSmileIcon />-->
<!--            </template>-->
<!--            <div style="display: flex">-->
<!--              <div>-->
<!--                团队消息-->
<!--              </div>-->
<!--              <div style="padding-left: 20px">-->
<!--                <t-tag shape="round" theme="danger">99+</t-tag>-->
<!--              </div>-->
<!--            </div>-->
<!--          </t-menu-item>-->
          <t-menu-item value="message_activity">
            <template #icon>
              <ChatMessageIcon />
            </template>
            <div style="display: flex">
              <div>
                活动动态
              </div>
              <div style="padding-left: 20px">
                <t-tag v-if="activityMessage.unreadCount !== 0" shape="round" theme="danger">{{activityMessage.unreadCount}}</t-tag>
              </div>
            </div>
          </t-menu-item>
        </t-menu-group>
        <t-menu-group title="个人">
          <t-menu-item value="user_info">
            <template #icon>
              <t-icon name="user"/>
            </template>
            个人页
          </t-menu-item>
          <t-menu-item value="login">
            <template #icon>
              <t-icon name="login"/>
            </template>
            登录页
          </t-menu-item>
        </t-menu-group>
        <template #operations>
          <t-button class="t-demo-collapse-btn" variant="text" shape="square" @click="changeCollapsed">
            <template #icon>
              <t-icon name="view-list"/>
            </template>
          </t-button>
        </template>
      </t-menu>
    </t-aside>

    <t-layout style="flex: 1; display: flex; flex-direction: column; height: 100%">
      <t-header style="background-color: rgba(0,82,217,1); flex-shrink: 0;">
        <!-- Header 内容 -->
      </t-header>
      <t-layout style="flex: 1; overflow-y: auto;">
        <t-content style="flex: 1; padding: 30px;">
          <router-view></router-view>
        </t-content>
        <t-footer style="background-color: rgba(0,82,217,1); color: white;">
          <div>
            Copyright @ 2024-{{
              new Date().getFullYear()
            }} HruiWorks. All Rights
            Reserved
          </div>
          <a style="color: white" :href="GONG_AN_BEI_AN_WEB" rel="noreferrer" target="_blank">
            <img src="/GongAnPic.png" alt="GongAnBeiAn" height="12">
            {{GONG_AN_BEI_AN_HAO}}
          </a>
          &nbsp;
          <a style="color: white" href="http://beian.miit.gov.cn/">{{ICP_BEI_AN_HAO}}</a>
          <div>
            <a style="color: white" :href="VITE_PROJECT_FRONT" rel="noreferrer" target="_blank">
              <img src="/gitee.png" alt="Gitee前端地址" height="12">
              项目前端地址
            </a>
            <a style="color: white" :href="VITE_PROJECT_BACKEND" rel="noreferrer" target="_blank">
              <img src="/gitee.png" alt="Gitee后端地址" height="12">
              项目后端地址
            </a>
          </div>
        </t-footer>
      </t-layout>
    </t-layout>
  </t-layout>
  <t-dialog
      v-model:visible="visible2"
      theme="success"
      header="活动开始提醒"
      body="对话框内容"
      :cancel-btn="null"
      :confirm-btn="null"
  >
    <template #body>
      <div v-html="dynamicHTML"></div>
    </template>
  </t-dialog>
  <t-dialog
      v-model:visible="showNotifyWindow"
      theme="info"
      header="提示"
      body="是否需要打开通知权限"
      @cancel="notify(false)"
      @confirm="notify(true)"
  />
</template>

<style scoped>


</style>